package com.douqu.game.main.msg;

import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.database.model.PlayerModel;
import com.douqu.game.core.entity.ArenaRank;
import com.douqu.game.core.entity.ext.ExtInfo;
import com.douqu.game.core.factory.WordFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGInstanceProto.*;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.entity.ext.ArenaInfo;
import com.douqu.game.main.database.mapper.PlayerMapper;
import com.douqu.game.main.server.GameServer;
import com.douqu.game.main.service.PlayerService;
import com.douqu.game.main.util.MsgUtils;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wangzhenfei
 *         2017-08-21 10:06
 *         竞技场消息
 */
@Component
public class ArenaMsgChannel implements AMsgChannel{
    Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private PlayerService playerService;

    @Override
    public void messageChannel(int code, PlayerController playerController, byte[] data) {
        //获取相应的数据
        if(playerController == null)
            return;
        
        switch (code)
        {
            case SGMainProto.E_MSG_ID.MsgID_Arena_GetArenaInfo_VALUE:
                getPlayerArenaRankInfo(playerController, data);
                break;

            case SGMainProto.E_MSG_ID.MsgID_Arena_Challenge_VALUE:
                arenaChallengeSuccess(playerController, data);
                break;
        }

    }



    private void getPlayerArenaRankInfo(PlayerController playerController, byte[] data) {
        S2C_ArenaGetArenaInfo.Builder response = S2C_ArenaGetArenaInfo.newBuilder();
        ArenaInfo arenaInfo = (ArenaInfo) playerController.getPlayer().getExtInfo(ArenaInfo.class);
        if(arenaInfo.getmArenaRank() == 0){ // 需要初始化到竞技场列表
            //获取最新的排名，在最后追加自己
            ArenaRank playerRank = GameServer.getInstance().getWorldManager().
                    addArenaRankInfo(playerController.getPlayer().getObjectIndex());
            arenaInfo.setmArenaRank(playerRank.getRank());
        }
        //自己的排名
        int myRank = arenaInfo.getmArenaRank();
        List<ArenaRank> rankList = getArenaRanksWithMe(myRank);
        for(ArenaRank rank : rankList){
            SGCommonProto.ArenaPlayerInfo.Builder builder = SGCommonProto.ArenaPlayerInfo.newBuilder();
            builder.setRank(rank.getRank());
            PlayerModel player = playerService.getPlayerByIndex(rank.getObjectIndex());
            if(player != null){
                builder.setName(player.getName());
                builder.setModel(player.getAvatar());
                builder.setFightingCapacity(player.getLevel());
            }else {
                logger.debug("根据玩家的索引无法查到玩家， 索引为: " +rank.getObjectIndex());
                //TODO ERROR
            }
            response.addPlayers(builder);
        }

        logger.info("返回给客户端关卡列表信息 ： " + response.toString());
        //返回给客户端
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Arena_GetArenaInfo_VALUE, response.build().toByteArray());

    }



    private void arenaChallengeSuccess(PlayerController playerController, byte[] data) {
        C2S_ArenaChallenge request = null;
        try {
            request = C2S_ArenaChallenge.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(SGCommonProto.E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        int targetRank = request.getTargetRank();
        ArenaInfo arenaInfo = (ArenaInfo) playerController.getPlayer().getExtInfo(ArenaInfo.class);
        int myRank = arenaInfo.getmArenaRank();
        logger.debug("arenaChallengeSuccess， myRank: " + myRank + ", targetRank: " + targetRank);
        if(targetRank > myRank){
            if(GameServer.getInstance().getWorldManager().swapArenaRank(myRank, targetRank)){
                S2C_ArenaChallenge.Builder response = S2C_ArenaChallenge.newBuilder();
                List<ArenaRank> rankList = getArenaRanksWithMe(myRank);
                for(ArenaRank rank : rankList){
                    SGCommonProto.ArenaPlayerInfo.Builder builder = SGCommonProto.ArenaPlayerInfo.newBuilder();
                    builder.setRank(rank.getRank());
                    PlayerModel player = playerService.getPlayerByIndex(rank.getObjectIndex());
                    if(player != null){
                        builder.setName(player.getName());
                        builder.setModel(player.getAvatar());
                        builder.setFightingCapacity(player.getLevel());
                    }else {
                        logger.debug("根据玩家的索引无法查到玩家， 索引为: " +rank.getObjectIndex());
                        //TODO ERROR
                    }
                    response.addPlayers(builder);
                }

                logger.info("返回给客户端关卡列表信息 ： " + response.toString());
                //返回给客户端
                playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Arena_Challenge_VALUE, response.build().toByteArray());
            }else{
                //TODO 交换位置失败
                logger.debug("交换位置失败");
            }
        }else{
            //TODO 目标位置比自己低
            logger.debug("目标位置比自己低");
        }
    }


    /**
     * 根据自己的排名获取竞技场排名情况
     * @param myRank
     * @return
     */
    private List<ArenaRank> getArenaRanksWithMe(int myRank) {
        List<ArenaRank> rankList = null;
        int paramY = 0;
        if(myRank < 16){//加载1-myRank的所有数据
            rankList = GameServer.getInstance().getWorldManager().getUnderTargetRankList(myRank);
        }else if(myRank < 31){
            paramY = 1;
        }else if(myRank < 101){
            paramY = 3;
        }else if(myRank < 501){
            paramY = 20;
        }else if(myRank < 1001){
            paramY = 30;
        }else if(myRank < 3001){
            paramY = 120;
        }else if(myRank < 6001){
            paramY = 200;
        }else {
            paramY = 300;
        }

        if(rankList == null){
            //取出前10名
            rankList = GameServer.getInstance().getWorldManager().getUnderTargetRankList(10);
            rankList.add(GameServer.getInstance().getWorldManager().getArenaRankInfo(myRank - 4 * paramY));
            rankList.add(GameServer.getInstance().getWorldManager().getArenaRankInfo(myRank - 3 * paramY));
            rankList.add(GameServer.getInstance().getWorldManager().getArenaRankInfo(myRank - 2 * paramY));
            rankList.add(GameServer.getInstance().getWorldManager().getArenaRankInfo(myRank - 1 * paramY));
        }
        return rankList;
    }
}
